package com.yanqu.road.web.util;

import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.string.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpAddressHelper {
    public static String getIpAddr(HttpServletRequest request) {

//        Enumeration<String> headerNames = request.getHeaderNames();
//        //获取获取的消息头名称，获取对应的值，并输出
//        while (headerNames.hasMoreElements()) {
//            String nextElement = headerNames.nextElement();
//            TempMgr.getLogger().error(nextElement + ":" + request.getHeader(nextElement));
//        }

        String ip = request.getHeader("X-real-ip");// 先从nginx自定义配置获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        try {
            String xTrueIp = request.getHeader("x-true-ip");
            if (!StringUtils.isNullOrEmpty(xTrueIp) && !"unknown".equalsIgnoreCase(ip)) {
//                TempMgr.getLogger().error(xTrueIp + ":" + ip);
                ip = xTrueIp;
            }
        } catch (Exception ex) {

        }

        try {
            if (ip == null) {
                ip = "114.114.114.114";
                TempMgr.getLogger().warn("get ip exception: default " + ip);
            }
        } catch (Exception ex) {
            TempMgr.getLogger().error("ip exception");
        }

        return ip;
    }
}
